<template>
  <div id="tab-bar">
    <div v-for="(item,index) in tabbar" :key="index" :class="item.className">
      <router-link
        :to="item.routerData"
        ref="tabItems"
        v-if="totalQuantity!==0&&item.title==='购物车'"
      >
        <div class="link-items">
          {{item.title}}
          <mt-badge size="small" type="success" class="quantity-badge">{{totalQuantity}}</mt-badge>
        </div>
      </router-link>
      <router-link
        :to="item.routerData"
        ref="tabItems"
        v-if="totalQuantity===0 || item.title!=='购物车'"
      >
        <div class="link-items">{{item.title}}</div>
      </router-link>
    </div>
  </div>
</template>
<script>
import "./index.less";
import { tabbar } from "../../config";
import { middleVue, shopcartData, userData } from "../../services";
import { each } from "lodash";
export default {
  data() {
    return {
      tabbar,
      totalQuantity: 0
    };
  },
  watch: {
    $route(to, from) {
      const currentRouteData = this.tabbar.find(
        item => item.routerData.name === to.name
      );
      if (currentRouteData) {
        this.$refs.tabItems.map(item => {
          item.$el.children[0].classList.remove("active");
          return item;
        });
        const currentItem = this.$refs.tabItems.find(item => {
          return item.$el.hash.indexOf(to.name) > -1;
        });
        currentItem.$el.children[0].classList.add("active");
      }
    }
  },
  created() {
    middleVue.$on("getTotalQuantity", totalQuantity => {
      this.totalQuantity = totalQuantity;
    });
    if (shopcartData.getShopcartData()) {
      each(shopcartData.getShopcartData(), item => {
        this.totalQuantity += item.quantity;
      });
    }
  },

  mounted() {
    // 通过接口查询在线购物车的数据，统计一个购物车里的商品数量的总和
    if (userData.getUserData()) {
      this.$axios
        .get("getshopcarts", {
          params: {
            account: userData.getUserData()
          }
        })
        .then(res => {
          each(res.data.message, item => {
            this.totalQuantity += item.quantity;
          });
        })
        .catch(err => console.log(err));
    }
  }
};
</script>